package com.cy.personer.web;
import com.alibaba.druid.support.spring.stat.annotation.Stat;
import com.cy.personer.bean.*;
import com.cy.personer.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.omg.CORBA.Request;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @施晓彬
 */

@Controller
@RequestMapping("/report")
public class ReportSxbHandler {
    @Resource
    private ReportSxbMapper reportSxbMapper;
    @Resource
    private RemarkMapper remarkMapper;
    @Resource
    private DetailMapper detailMapper;
    @Resource
    private ReportDetailSxbMapper reportDetailSxbMapper;
    @Resource
    private ReportitemDetail reportitemDetail;
    @Resource
    private Report report;
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private OperationUserMapper operationUserMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private cardSxbMapper cardSxbMapper;
    @Resource
    private SuggestMapper suggestMapper;
    @Resource
    private SummaryMapper summaryMapper;

    /**
     * 跳转到输入卡片页面
     */
    @RequestMapping(value = "/inputCardNumber.action")
    public String inputCardNumber(HttpServletRequest request) {
        return "admin/input_cardNumber";
    }
    /**
     * 输入卡号进行ajax判断
     * @param cardNumber
     * @return
     */
    @RequestMapping(value="/checkCard.action", method=RequestMethod.POST,produces = "application/json;charset=utf-8" )
 public @ResponseBody String checkCard(HttpSession session,Integer cardNumber){
        Card card = cardSxbMapper.getCard(cardNumber);
        if(card!=null){
            User user = cardSxbMapper.getUser(card.getCardId());
            session.setAttribute("user",user);
            return "true";
        }else{
            return "false";
        }
    }

    /**
     * sxb根据用户查询所有报告项目列表
     *
     * @param request
     * @param num
     * @return
     */
    @RequestMapping(value = "/reportList.action")
    public String remarkList(HttpServletRequest request, Integer num) {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        Work work=(Work)session.getAttribute("work");
        if (num == null || num == 0) {
            num = 1;
        }
        PageHelper.startPage(num, 5);
        List<ReportItem> reportItems = reportSxbMapper.reportItemListSxb1(user.getUserId(), work.getWorkId(), 16,17);
        PageInfo<ReportItem> page = new PageInfo<>(reportItems);
        request.setAttribute("page", page);
        return "admin/reportItem_list";

    }
//未结算扣款
    @RequestMapping(value = "/reportBalance.action", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public @ResponseBody String reportBalance(HttpServletRequest request,Integer reportItemId) {
        ReportItem reportItem = reportSxbMapper.getReportItem(reportItemId);
        Item item = reportSxbMapper.getItem(reportItem.getItemId());
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        double userMoney = user.getUserMoney();
        double money1 = userMoney - (double) item.getItemMoney();
        if (money1 > 0) {
            user.setUserMoney(money1);
            reportSxbMapper.updateReportItemId(reportItemId, reportItem.getStateId()+1);
            reportSxbMapper.updataUserMoney(user);
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * 根据不同项目返回类型：返回不同数据结果
     *
     * @param request
     * @param reportItemId
     * @param
     * @param
     */
    @RequestMapping("upItemState.action")
    public String upItemState(HttpServletRequest request, Integer reportItemId, Integer num) {
        ReportItem reportItem1 = reportSxbMapper.getReportItem(reportItemId);
        Item item1 = reportSxbMapper.getItem(reportItem1.getItemId());
        HttpSession session = request.getSession();
        Work work = (Work)session.getAttribute("work");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String checkTime = sdf.format(new Date());
        boolean b = reportSxbMapper.setReportItemWork(work.getWorkId(), checkTime, reportItemId);
        if (num == null || num == 0) {
            num = 1;
        }
        /**
         * 开始体检
         */
        if (reportItem1.getStateId() == 17) {
            PageHelper.startPage(num, 3);
            List<Detail> itemdetails = reportSxbMapper.findItemdetails(item1.getItemId());
            PageInfo<Detail> page = new PageInfo<>(itemdetails);
            request.setAttribute("page", page);
            request.setAttribute("resultType", item1.getResultType());
            request.setAttribute("reportItemId", reportItemId);
            request.setAttribute("itemStateId", item1.getStateId());
            //根据itemId查询出所有细项以及结果值
            return "admin/detail_result";

        }
        return "admin/detail_result";
    }


    /**
     * 确认添加体检结果到数据库中sxb
     *
     * @param request
     * @param reportItemId
     * @param
     */
    @RequestMapping("reportSubmit.action")
    public String reportSubmit(HttpServletRequest request, Integer reportItemId,
                               Integer[] detailResult, Integer[] detailsId) {
        ReportItem reportItem = reportSxbMapper.getReportItem(reportItemId);
        Item item = reportSxbMapper.getItem(reportItem.getItemId());
        boolean b = false;
        //批量添加
        for (int i = 0; i < detailsId.length; i++) {
            reportitemDetail.setDetailId(detailsId[i]);
            reportitemDetail.setResult(String.valueOf(detailResult[i]));
            reportitemDetail.setReportItemId(reportItemId);
            b = reportDetailSxbMapper.addReportDetail(reportitemDetail);
        }
        if (b) {
            Integer stateId = reportItem.getStateId() + 1;
            boolean c = reportSxbMapper.updateReportItemId(reportItemId, stateId);
        }
        return "forward:/report/reportList.action";
    }

    /**
     * 出现小结列表
     */
    @RequestMapping("/remarkSubmit1.action")
                public String addRemark(HttpServletRequest request,Integer num,User user){
        HttpSession session = request.getSession();
//       User user = (User)session.getAttribute("user");
        Work work=(Work)session.getAttribute("work");
        if (num == null || num == 0) {
            num = 1;
        }
        State state = new State();
        state.setStateId(18);
        PageHelper.startPage(num, 5);
        List<ReportItem> reportItems = reportSxbMapper.reportItemListSxb(user,work,state);
        PageInfo<ReportItem> page = new PageInfo<>(reportItems);
        request.setAttribute("page", page);
        return "admin/beforeRemark";
        }
    /**
     * 显示体检结果并且显示需要添加小结的界面
     */
    @RequestMapping("/addRemark.action")
    public String dd(HttpServletRequest request,Integer num,Integer reportItemId,Desk desk){
        HttpSession session = request.getSession();
        ReportItem reportItem = reportSxbMapper.getReportItem(reportItemId);
        Work work=(Work) session.getAttribute("work");
        Item item = reportSxbMapper.getItem(reportItem.getItemId());
        String resultType1 = item.getResultType();
            List<Remark> remarks = remarkMapper.remarkList(work,desk);
            request.setAttribute("remarks", remarks);
            if(num==null){
                num=1;
            }
            PageHelper.startPage(num, 3);
            List<ReportitemDetail> reportitemDetails = reportDetailSxbMapper.reportDetails(reportItemId);
            PageInfo<ReportitemDetail> page = new PageInfo<>(reportitemDetails);
            request.setAttribute("page", page);
            String result=null;
               for(int i=0;i<reportitemDetails.size();i++){
                 result = reportitemDetails.get(i).getResult();
               }
               request.setAttribute("result",result);
               request.setAttribute("resultType",resultType1);
                session.setAttribute("reportItemId1", reportItemId);
                session.setAttribute("itemStateId1", item.getItemId());
                return "admin/add_remark";
    }

    /**
     * 添加小结到数据库中并且要纪录小结的时间
     *
     * @param request
     * @param reportItemId
     * @param remarkField
     * @param
     * @return
     */
    @RequestMapping("remarkSubmit.action")
    public String remarkSubmit(HttpServletRequest request, Integer reportItemId, String remarkField) {
        //在报告项目表中添加评语
        ReportItem reportItem = reportSxbMapper.getReportItem(reportItemId);
        Item item = reportSxbMapper.getItem(reportItem.getItemId());
        boolean b1 = reportSxbMapper.updateRemark(reportItemId, remarkField);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = sdf.format(new Date());
        reportSxbMapper.setReportItemEnd(endTime,reportItemId);
        if (b1) {
            Integer stateId = reportItem.getStateId() + 1;
            boolean c = reportSxbMapper.updateReportItemId(reportItemId, stateId);
            List<ReportItem> reportItems = reportSxbMapper.reportInformation(reportItem.getReportId());
            //根据报告id查询是否全部已体检
//            for (int i = 0; i < reportItems.size(); i++) {
//                Integer stateId1 = reportItems.get(i).getStateId();
//                if (stateId1 != 19) {
//                    break;
//                }
//                if (i == reportItems.size() - 1) {
//                    reportSxbMapper.updateReportState(reportItem.getReportId(), 13);
//                    return "forward:/report/reportList1.action";
//                }
//            }
        }
        return "forward:/report/remarkSubmit1.action";
    }

    /**
     *显示所有需要写总结的报告
     */
    @RequestMapping("allReport.action")
    public String allReport(HttpServletRequest request,Integer num){
        if(num==null||num==0){
            num=1;
        }
        List<Report> reports = reportSxbMapper.allReport();
        List<Report> reports1=new ArrayList<Report>();
        for(int i=0;i<reports.size();i++){
            if(reports.get(i).getStateId()==11){
                List<ReportItem> reportItems = reportSxbMapper.reportInformation(reports.get(i).getReportId());
//        只要报告里面有一个体检项还没有小结的就把它移除掉
                for (int j = 0; j < reportItems.size(); j++) {
                    Integer stateId1 = reportItems.get(j).getStateId();
                    if (stateId1 != 19) {
                        break;
                    }
                    //所有的项目都已经小结
                    if (j == reportItems.size() - 1) {
                        reports1.add(reports.get(i));
                    }
                }
            }
        }
        request.setAttribute("reports1",reports1);
        return "admin/allReport_list";
    }

    /**
     * 显示总结提交页面sxb*************************************************************************
     */
    @RequestMapping("/allRemark.action")
    public String allRemark(HttpServletRequest request, Integer reportId, Integer num) {
        request.setAttribute("reportId", reportId);
        //根据报告Id查询出来所有的报告项目小结
        if (num == null || num == 0) {
            num = 1;
        }
        PageHelper.startPage(num, 2);
        List<ReportItem> reportItems = reportSxbMapper.reportInformation(reportId);
        PageInfo<ReportItem> page = new PageInfo<>(reportItems);
        request.setAttribute("page", page);
        List<Suggest> suggests = reportSxbMapper.getSuggests();
        request.setAttribute("suggests",suggests);
        List<Summary> summarys = reportSxbMapper.getSummarys();
        request.setAttribute("summarys", summarys);
        return "admin/add_allRemark";
    }

    /**
     * 提交总结提交页面sxb*************************************************************************
     */
    @RequestMapping("/addFinally.action")
    public String addFinally(HttpServletRequest request, Integer reportId,String suggest, String guidance) {
        //添加内容：并且更改状态
        HttpSession session = request.getSession();
        report.setReportId(reportId);
        Report report1 = reportSxbMapper.queryReport(reportId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = sdf.format(new Date());
        report.setEndTime(endTime);
        report.setStateId(14);
        Work work=(Work) session.getAttribute("work");
        report.setGuidanceId(work.getWorkId());
        this.report.setSuggest(suggest);
        this.report.setGuidance(guidance);
        boolean b = reportSxbMapper.updateFinallyReport(report);
        return "forward:/report/allReport.action";
    }

    /**
     *显示所有的报告：无论是谁的******************************************************
     */
    @RequestMapping("/reportManage.action")
    public String reportManage(HttpServletRequest request, User user, State state ,Integer num) {
        if(num==null||num==0){
            num=1;
        }
        PageHelper.startPage(num,7);
        List<Report> reports = reportSxbMapper.reports(state,user);
        PageInfo<Report> page = new PageInfo<>(reports);
        request.setAttribute("page",page);
        return "admin/reportManage_list";
    }

    //根据报告id显示出该报告详情
    @RequestMapping("/reportImformation.action")
    public String reportImformation(HttpServletRequest request,Integer num,Integer reportId){
        if(num==null||num==0){
            num=1;
        }
        request.setAttribute("reportId",reportId);
        Report report = reportSxbMapper.queryReport(reportId);
        User user = cardSxbMapper.getUser(report.getUserId());
        request.setAttribute("user",user);
        PageHelper.startPage(num,3);
        List<ReportItem> reportItems = reportSxbMapper.reportInformation1(reportId);
        PageInfo<ReportItem> page = new PageInfo<>(reportItems);
        request.setAttribute("page",page);
        return "admin/reportImformation";
    }

    //门户上根据userId显示所有报告和导检单打印
    @RequestMapping("/userReport.action")
    public String userReport(HttpServletRequest request,Integer num) {
        if(num==null||num==0){
            num=1;
        }
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        PageHelper.startPage(num,10);
        List<Report> reports = reportSxbMapper.userReports(user);
        PageInfo<Report> page = new PageInfo<>(reports);
        request.setAttribute("page",page);
        return "admin/reportManage_list";
    }

    //上传图片
    @RequestMapping("/upload.action")
    public String upload(HttpSession session, MultipartFile file,Integer name) throws Exception {
        //定义文件保存的路径
        String localPath = session.getServletContext().getRealPath("/resultImg");
        //定义 文件名
        String filename = null;
        if (!file.isEmpty()) {
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType = file.getContentType();
            //获得文件后缀名
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            //得到 文件名
            filename = String.valueOf(name) + "." + suffixName;
            File file1 = new File(localPath,filename);
            boolean newFile = file1.createNewFile();
            if (newFile) {
                //文件保存路径
                file.transferTo(file1);
            }
        }
        //把图片的保存至数据库的路径
        String keyword = "resultImg/"+filename;//文件名
        //根据文件名得到所有的该报告项目表的细线：name
        //通过项目中间查询到itemId
        ReportItem reportItem = reportSxbMapper.getReportItem(name);
        List<Detail> itemdetails = reportSxbMapper.findItemdetails(reportItem.getItemId());
        Integer  reportId=reportItem.getReportId();
        for(int i=0;i<itemdetails.size();i++){
            reportitemDetail.setResult(keyword);
            reportitemDetail.setReportItemId(name);
            reportitemDetail.setDetailId(itemdetails.get(i).getDetailId());
            reportDetailSxbMapper.addReportDetail(reportitemDetail);
        }
        reportSxbMapper.updateReportItemId(name,18);
        return "forward:/report/reportList.action";
    }




//        else if (reportItem1.getStateId() == 18) {
//            //根据reportItemId得到Ite
//            String resultType1 = item1.getResultType();
//            List<Remark> remarks = remarkMapper.remarkList();
//            request.setAttribute("remarks", remarks);
//            PageHelper.startPage(num, 3);
//            List<ReportitemDetail> reportitemDetails = reportDetailSxbMapper.reportDetails(reportItemId);
//            PageInfo<ReportitemDetail> page = new PageInfo<>(reportitemDetails);
//            request.setAttribute("page", page);
//            //如果输入的是图片的话
//            String result=null;
//               for(int i=0;i<reportitemDetails.size();i++){
//                 result = reportitemDetails.get(i).getResult();
//               }
//               request.setAttribute("result",result);
//               request.setAttribute("resultType",resultType1);
//                session.setAttribute("reportItemId1", reportItemId);
//                session.setAttribute("itemStateId1", item1.getItemId());
//                //根据报告项目id（reportItemId）查询出项目报告细项表
//                return "admin/add_remark";
//        }
//        return "forward:/report/reportInformation.action?reportId=" + reportItem1.getReportId();


}
